<template>
  <div class="login-container">
    <div class="login-box">
      <!-- Logo 和标题 -->
      <div class="logo-section">
        <img src="@/assets/logo.png" alt="盒游纪"/>
        <div class="title">
          <h2>盒游纪后台管理系统</h2>
          <p>Vue3.x 企业级信息管理系统</p>
        </div>
      </div>

      <!-- 登录表单 -->
      <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" label-width="0">
        <el-form-item prop="adminAccount">
          <el-input
              v-model="loginForm.adminAccount"
              placeholder="账号"
              :prefix-icon="User"
              clearable
          />
        </el-form-item>

        <el-form-item prop="adminPassword">
          <el-input
              v-model="loginForm.adminPassword"
              type="password"
              placeholder="密码"
              :prefix-icon="Lock"
              show-password
          />
        </el-form-item>

        <!-- 同意服务条款 -->
        <div class="terms">
          <el-checkbox v-model="loginForm.agreeTerms" checked-color="#00bfff">
            登录表示您已同意
            <span class="terms-link" @click="showTerms">《盒游纪服务条款》</span>
          </el-checkbox>
        </div>

        <el-form-item>
          <el-button
              type="primary"
              @click="handleLogin"
              :loading="loading"
              :disabled="!loginForm.agreeTerms"
          >
            立即登录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue';
import axios from '@/utils/axios';
import {useRouter} from 'vue-router';
import {User, Lock} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';


// 路由实例，用于页面跳转
const router = useRouter();

// 表单数据接口定义
interface LoginFormData {
  adminAccount: string;
  adminPassword: string;
  agreeTerms: boolean;
}

// 登录表单响应式数据
const loginForm = reactive<LoginFormData>({
  adminAccount: '',
  adminPassword: '',
  agreeTerms: false
});

// 控制登录按钮加载状态的响应式变量
const loading = ref(false);

// 表单校验规则配置
const loginRules = {
  adminAccount: [
    {required: true, message: '请输入账号', trigger: 'blur'}
  ],
  adminPassword: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 6, message: '密码长度不能少于6位', trigger: 'blur'}
  ]
};

// 登录表单地引用，用于调用表单方法
const loginFormRef = ref();

// 页面加载时尝试恢复表单数据
onMounted(() => {
  // 尝试恢复表单数据
  const savedFormData = sessionStorage.getItem('loginFormData');
  if (savedFormData) {
    try {
      const parsedData = JSON.parse(savedFormData);
      loginForm.adminAccount = parsedData.adminAccount || '';
      loginForm.adminPassword = parsedData.adminPassword || '';
      loginForm.agreeTerms = parsedData.agreeTerms || false;
      // 恢复后清除存储的数据
      sessionStorage.removeItem('loginFormData');
    } catch (e) {
      console.error('Failed to parse saved form data', e);
    }
  }
});

// 监听表单数据变化并保存到 sessionStorage
const saveFormData = () => {
  sessionStorage.setItem('loginFormData', JSON.stringify({...loginForm}));
};

/**
 * 显示服务条款信息
 * 该函数用于在用户点击服务条款时跳转到服务条款页面
 */
const showTerms = () => {
  // 保存当前表单数据
  saveFormData();
  router.push('/terms?from=login');
};

/**
 * 处理用户登录逻辑
 * 包含表单校验、发送登录请求、存储token和页面跳转等操作
 */
const handleLogin = async () => {
  if (!loginForm.agreeTerms) {
    ElMessage.error('请先同意服务条款');
    return;
  }

  try {
    // 校验表单
    await new Promise<void>((resolve, reject) => {
      loginFormRef.value.validate((valid: boolean) => {
        if (valid) {
          resolve();
        } else {
          reject(new Error('表单验证失败'));
        }
      });
    });

    loading.value = true;

    // 准备登录数据，使用正确的字段名
    const loginData = {
      adminAccount: loginForm.adminAccount,
      adminPassword: loginForm.adminPassword
    };

    // 发送登录请求
    const response = await axios.post('/admin/login', loginData);

    // 如果成功，axios拦截器会返回处理后的数据（code为200）
    // 存储token
    localStorage.setItem('token', response.data.token);
    ElMessage.success('登录成功');
    router.push('/main/dashboard');
  } catch (error: any) {
    // axios拦截器会处理错误信息并显示，这里不需要重复处理
    // 只需要处理特殊情况或添加额外的错误处理逻辑
    if (error.message !== '表单验证失败') {
      console.error('Login error:', error);
    }
  } finally {
    loading.value = false;
  }
};

</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
  padding: 20px;
  position: relative;
  height: 100vh;
  overflow: hidden;
}

.login-box {
  width: 100%;
  max-width: 400px;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background: white;
  z-index: 100;
}

.logo-section {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 30px;
  flex-direction: column;
}

.logo-section img {
  width: 80px;
  height: 80px;
  margin-right: 0;
  margin-bottom: 15px;
}

.logo-section .title {
  text-align: center;
}

.logo-section .title h2 {
  color: #00bfff;
  font-size: 24px;
  margin: 0;
}

.logo-section .title p {
  color: #999;
  font-size: 12px;
  margin: 5px 0 0;
}

.terms {
  font-size: 12px;
  color: #666;
  text-align: center;
  margin: 15px 0;
}

.terms-link {
  color: #00bfff;
  cursor: pointer;
}

.el-button {
  width: 100%;
}

:deep(.el-button:disabled) {
  opacity: 0.6;
}
</style>
